In this quick article, we will understand what is @SpringBootTest and @WebMvcTest annotations and the differences between them.
Before understanding the difference between @SpringBootTest and @WebMvcTest annotations, let's first take a look at a quick overview of these two annotations.
Spring Boot provides @SpringBootTest annotation for Integration testing. This annotation creates an application context and loads the full application context.
@SpringBootTest will bootstrap the full application context, which means we can @Autowire any bean that's picked up by component scanning into our test.
It starts the embedded server, creates a web environment, and then enables @Test methods to do integration testing.
By default, @SpringBootTest does not start a server. We need to add the attribute webEnvironment to further refine how your tests run. It has several options:
SpringBoot provides @WebMvcTest annotation to test Spring MVC Controllers. Also, @WebMvcTest based test run faster because it will load only the specified controller and its dependencies only without loading the entire application.
Spring Boot instantiates only the web layer rather than the whole application context. In an application with multiple controllers, you can even ask for only one to be instantiated by using, for example, @WebMvcTest(HomeController.class).
1. @SpringBootTest annotation loads the full application context so that we can able to test various components. So basically, the @SpringBootTest annotation tells Spring Boot to look for the main configuration class (one with @SpringBootApplication, for instance) and use that to start a Spring application context.
@WebMvcTest annotation loads only the specified controller and its dependencies only without loading the entire application. For example, let's say you have multiple Spring MVC controllers in your Spring boot project - EmployeeController, UserController, LoginController, etc then we can use @WebMvcTest annotation to test only specific Spring MVC controllers without loading all the controllers and their dependencies.
2. Spring Boot provides @SpringBootTest annotation for Integration testing.
Spring boot provides @WebMvcTest annotation for testing Spring MVC controllers (Unit testing).
Usage of @SpringBootTest annotation demonstrated in the below tutorial:
Spring Boot Integration Testing MySQL CRUD REST API Tutorial
Usage of @WebMvcTest annotation demonstrated in the below tutorial:
Spring Boot Unit Testing CRUD REST API with JUnit and Mockito
Spring Boot Testing - Data Access Layer Integration Testing using Testcontainers
Spring Boot Testing - REST API Integration Testing using Testcontainers
Spring Data JPA Repository Testing using Spring Boot @DataJpaTest
CRUD JUnit Tests for Spring Data JPA - Testing Repository Layer
Spring Boot Unit Testing CRUD REST API with JUnit and Mockito
Spring Boot Integration Testing MySQL CRUD REST API Tutorial
Spring Boot Unit Testing Service Layer using JUnit and Mockito